#ifndef MASTER_H_
#define MASTER_H_

#include <iostream>
#include <string>
#include <unordered_map>
#include <uv.h>

#include "spidernode.h"

typedef struct {
    uv_buf_t userName;
    uv_buf_t msg;
} task_data_t;

class Master {
public:
    int m_spiderPort;
    int m_webPort;
    int m_interval;
    int m_commandTimeout;
    int m_idleTimeout;
    uv_thread_t m_masterTid;

    uv_loop_t *m_masterLoop;
    uv_tcp_t m_spiderServer;
    uv_tcp_t m_webServer;

    std::unordered_map<std::string, SpiderNode *> m_spiderCache;

public:    
    Master() = default;
    ~Master() = default;
    bool Init(int spiderPort, int webPort, int interval, int commandTimeout, int idleTimeout);
    bool Start();
    void Stop();

    uv_loop_t *GetLoop() {
        return m_masterLoop;
    };
    
    void RunLoop();
    void OnRecvConnection(uv_stream_t* pServer);
    void OnRecvWebConnection(uv_stream_t* pServer);

    bool AddSpiderNodeCache(SpiderNode *pNode);
    void DelSpiderNodeCache(SpiderNode *pNode);

    void DoMsgToSpiderNode(std::string uuid, char* msg, uint16_t msgLen);
    void DoSendMsgToSpiderNode(task_data_t *data);
};

#endif